import { observable, action } from 'mobx'
import * as api from 'lib/constants/api'
import { post } from 'lib/net'
import Toast from 'components/toast'
import Load from 'components/load'

// class AddressModel {
//   constructor (data) {
//     if (data) {
//     }
//   }
// }

export default class CenterVM {
  constructor (props) {
    this.props = props
    this.tabBarList()
  }

  // 获取手机号
  @observable phoneNumber = ''

  // 获取密码
  @observable password = ''

  // 获取手机号、密码
  @action onChange = (v, key) => {
    switch (key) {
      case 'Phone':
        this.phoneNumber = v
        break
      case 'Password':
        this.password = v
        break
    }
  }

  // 验证手机号是否符合正则
  @action phoneCodeValid = (number) => {
    if (number) {
      this.number = number
      this.number = Number(this.myTrim(this.number, 'g'))
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!myreg.test(this.number)) {
        Toast.fail('请输入正确手机号')
        return false
      } else {
        return true
      }
    } else {
      Load.loading(2, '登录失败')
      Toast.fail('请输入正确手机号')
      return false
    }
  }

  // 去除字符串中的空格
  @action myTrim = (str, global) => {
    if (str) {
      let result
      result = str.toString().replace(/(^\s+)|(\s+$)/g, '')
      if (global.toLowerCase() === 'g') {
        result = result.replace(/\s/g, '')
      }
      return result
    } else {
      return false
    }
  }

  // 跳转到忘记密码
  @action handleToForgetPassword = async () => {
    this.props.history.push('/passwordForget')
  }

  // 登录页面
  @action handleSignin = async () => {
    if (this.phoneCodeValid(this.phoneNumber) === false) {
      return false
    } else if (this.myTrim(this.password, 'g') === '') {
      Toast.fail('请输入密码')
    } else {
      let params = {
        PhoneNum: this.myTrim(this.phoneNumber, 'g'),
        PassWord: this.password
      }
      Load.loading(1, '登录中')
      let response = await post(api.WZLOGIN, params)
      this.props.children.userValue = response.Value
      if (response.Success) {
        Load.loading(2, '登录完成')
        window.localStorage.setItem('WZUserName', this.myTrim(this.phoneNumber, 'g'))
        window.localStorage.setItem('WZPassWord', this.password)
        this.props.history.push('/projectList')
        window.localStorage.setItem('UserId', response.Value.Id)
      } else {
        Load.loading(2, '登录失败')
        Toast.fail(response.Message)
      }
    }
  }

  @action tabBarList = async () => {
    this.phoneNumber = window.localStorage.getItem('WZUserName')
    this.password = window.localStorage.getItem('WZPassWord')
    // const UserId = window.localStorage.getItem('UserId')
    // if (this.phoneNumber !== '' && this.password !== '' && UserId) {
    //   this.props.history.push('/projectList')
    // }
  }
}
